package com.strangebreeds.tfh.status;

import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSubscriber;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class StatusClientTest
{
	TopicConnection conn = null;
	TopicSession session = null;
	Topic topic = null;

	public void setupPubSub() throws JMSException, NamingException
	{
		Properties properties = new Properties();
		properties.put(	Context.INITIAL_CONTEXT_FACTORY,
						"org.jnp.interfaces.NamingContextFactory");
		properties.put(	Context.URL_PKG_PREFIXES,
						"org.jboss.naming:org.jnp.interfaces");
		properties.put(Context.PROVIDER_URL, "localhost:1099");
		Context iniCtx = new InitialContext(properties);

		// InitialContext iniCtx = new InitialContext();
		Object tmp = iniCtx.lookup("ConnectionFactory");
		TopicConnectionFactory tcf = (TopicConnectionFactory) tmp;
		conn = tcf.createTopicConnection();
		topic = (Topic) iniCtx.lookup("topic/tfh_status_topic");
		session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
		conn.start();
	}

	public void recvSync() throws JMSException, NamingException
	{
		System.out.println("Begin recvSync");
		// Setup the pub/sub connection, session
		setupPubSub();
		// Wait upto 5 seconds for the message
		TopicSubscriber recv = session.createSubscriber(topic);

		// Will sit forever looking for messages on the zestyTopic
		while (true)
		{
			Message msg = recv.receive(5000);
			if (msg == null)
			{
				System.out.println("Timed out waiting for msg");
			}
			else
			{
				System.out.println("TopicSubscriber.recv, msgt=" + msg);
				MapMessage mm = null;

				mm = (MapMessage) msg;
				System.out.println("Job ID " + mm.getInt("jobID") + " is working on "
						+ mm.getString("pageName") + " which is type " + mm.getString("pageType"));
			}
		}
	}

	public void stop() throws JMSException
	{
		conn.stop();
		session.close();
		conn.close();
	}

	public static void main(String args[]) throws Exception
	{
		System.out.println("Begin StatusClientTest, now="
				+ System.currentTimeMillis());
		StatusClientTest client = new StatusClientTest();
		client.recvSync();
		client.stop();
		System.out.println("End StatusClientTest");
		System.exit(0);
	}
}
